/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.service;

import java.util.List;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.boxin.ims.modules.wechat.entity.UserDefine;
import com.boxin.ims.modules.wechat.dao.UserDefineDao;

import freemarker.template.utility.HtmlEscape;

/**
 * 用户全局配置Service
 * @author Jakemanse
 * @version 2013-10-03
 */
@Component
@Transactional(readOnly = true)
public class UserDefineService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(UserDefineService.class);
	
	@Autowired
	private UserDefineDao userDefineDao;
	
	public UserDefine get(Long id) {
		return userDefineDao.findOne(id);
	}
	
	public UserDefine getByUserId(Long userId){
		DetachedCriteria dc = userDefineDao.createDetachedCriteria();
		dc.add(Restrictions.eq("user.id", userId));
		List<UserDefine> result = userDefineDao.find(dc);
		return (result == null || result.isEmpty()) ?null: result.get(0);
	}
	
	public Page<UserDefine> find(Page<UserDefine> page, UserDefine userDefine) {
		DetachedCriteria dc = userDefineDao.createDetachedCriteria();
		if (userDefine.getUser()!=null && userDefine.getUser().getId()>0){
			dc.add(Restrictions.eq("user.id", userDefine.getUser().getId()));
		}
		if (StringUtils.isNotEmpty(userDefine.getName())){
			dc.add(Restrictions.like("name", "%"+userDefine.getName()+"%"));
		}
		if (StringUtils.isNotEmpty(userDefine.getRemarks())){
			dc.add(Restrictions.like("remarks", "%"+userDefine.getRemarks()+"%"));
		}
		dc.add(Restrictions.eq("delFlag", UserDefine.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return userDefineDao.find(page, dc);
	}
	
	@Transactional(readOnly = false)
	public void save(UserDefine userDefine) {
		
		userDefine.setFooter(StringEscapeUtils.unescapeHtml4(userDefine.getFooter()));
		userDefineDao.save(userDefine);
	}
	
	@Transactional(readOnly = false)
	public void delete(Long id) {
		userDefineDao.deleteById(id);
	}
	
}
